//
//  KeyboardEmoticonViewController.swift
//  customKeyboard
//
//  Created by changhongliang on 2017/8/12.
//  Copyright © 2017年 richinfo. All rights reserved.
//

import UIKit
import SnapKit

class KeyboardEmoticonViewController: UIViewController {
    
    var emoticonDidSelectedCallback: (_ emoticon: KeyboardEmoticon)->()
    init(callback: @escaping (_ emoticon: KeyboardEmoticon)->()){
        emoticonDidSelectedCallback = callback
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: -内部控制方法
    private func setupUI(){
     //1.添加子控件
        view.addSubview(collectionView)
        collectionView.addSubview(alertLabel)
        alertLabel.snp.makeConstraints({ (make) in
            make.center.equalTo(collectionView)
        })
        alertLabel.sizeToFit()
        //添加pagecontrol
        view.addSubview(pageControl)
        //pageControl 只需要设置位置和页面数目,还有当前页面的小圆点的颜色,和其他页面的颜色
        pageControl.numberOfPages = emotionPackages.count
        pageControl.currentPageIndicatorTintColor = UIColor.orange
        pageControl.pageIndicatorTintColor = UIColor.lightGray
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(view).offset(-34)
        }
        
        
        view.addSubview(toolBar)
     //2.布局子控件
        collectionView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
        }
        toolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(collectionView.snp.bottom)
            make.height.equalTo(44)
            
        }
        
    }
    
    
    // MARK: -懒加载
   private lazy var collectionView:UICollectionView = {
        let clv = UICollectionView(frame: CGRect.zero, collectionViewLayout:KeyboardEmoticonLayout())
        clv.register(KeyboardEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: "myEmoticonCell")
        clv.backgroundColor = UIColor.white
        clv.dataSource = self
        clv.delegate = self
        return clv
    }()
    
    private lazy var toolBar:UIToolbar = {
        let tb = UIToolbar()
        tb.tintColor = UIColor.darkGray
        var items = [UIBarButtonItem]()
        var index = 0
        for title in ["最近","默认","Emoji","浪小花"]{
        
            let item = UIBarButtonItem(title: title, style:UIBarButtonItemStyle.plain, target: self, action: #selector(KeyboardEmoticonViewController.buttonItemClick(item:)))
            index += 1
            item.tag = index
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target:nil, action: nil))
        }
        items.removeLast()
        tb.items = items
        return tb
    }()
    
    lazy var alertLabel:UILabel = UILabel(title: "暂不最近表情~")
    lazy var pageControl: UIPageControl = UIPageControl(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    
    func buttonItemClick(item: UIBarButtonItem){
        let path = IndexPath(item: 0, section: item.tag - 1)
        collectionView.scrollToItem(at:path, at: UICollectionViewScrollPosition.left, animated: true)
        //设置pagecontrol
        pageControl.currentPage = item.tag - 1
    }
    
   fileprivate lazy var emotionPackages = KeyboardEmoticonPackage.loadPackages()
    
   }

extension KeyboardEmoticonViewController : UICollectionViewDataSource,UICollectionViewDelegate
{
    // 告诉系统有多少组
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return emotionPackages.count
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emotionPackages[section].emotions?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myEmoticonCell", for: indexPath)as! KeyboardEmoticonCollectionViewCell
        cell.emoticon = emotionPackages[indexPath.section].emotions?[indexPath.item]
        //设置pagecontrol
//        pageControl.currentPage = indexPath.section
//        print("pageControl.currentPage:\(indexPath.section)")
        return cell
    }
    
    // MARK: - UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let emoticon = emotionPackages[indexPath.section].emotions?[indexPath.item]
        emoticonDidSelectedCallback(emoticon!)
        // 2.将表情放入最近
        if indexPath.section != 0 && !(emoticon!.isRemoveButton) && ((emoticon?.imagePath != nil) || (emoticon?.codeStr != nil))
        {
            emotionPackages[0].addFavoriteEmoticon(emoticon: emoticon!)
            if !alertLabel.isHidden {
                alertLabel.isHidden = true
            }
            collectionView.collectionViewLayout.invalidateLayout()
            collectionView.reloadData()
        }

    }

    
}


//class KeyboardEmoticonLayout: UICollectionViewFlowLayout{

class KeyboardEmoticonLayout: emoticonLayout{
    override func prepare() {
        super.prepare()
        //1.计算宽度
        let width = UIScreen.main.bounds.width / 7
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.isPagingEnabled = true
        //注意:如果是在iphone 4/4s上乘以0.5会有问题
        let offsetY = (collectionView!.frame.height - 3 * width) * 0.49
        collectionView?.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
    }

//    override func prepare() {
//        super.prepare()
//        //1.计算宽度
//        let width = UIScreen.main.bounds.width / 7
//        itemSize  = CGSize(width: width, height: width)
//        minimumInteritemSpacing = 0
//        minimumLineSpacing = 0
//        scrollDirection = UICollectionViewScrollDirection.horizontal
//        collectionView?.showsVerticalScrollIndicator = false
//        collectionView?.showsHorizontalScrollIndicator = false
//        collectionView?.isPagingEnabled = true
//        //注意:如果是在iphone 4/4s上乘以0.5会有问题
//        let offsetY = (collectionView!.frame.height - 3 * width) * 0.49
//        collectionView?.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
//    }
}

